package example.TCPTest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class SimpleTcpClient {
    public static void main(String[] args) {
        String hostname = "localhost";
        int port = 8888;
        
        try (Socket socket = new Socket(hostname, port);
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             BufferedReader in = new BufferedReader(
                 new InputStreamReader(socket.getInputStream()));
             BufferedReader stdIn = new BufferedReader(
                 new InputStreamReader(System.in))) {
            
            System.out.println("已连接到服务器 " + hostname + ":" + port);
            
            String userInput;
            System.out.print("请输入消息 (输入 'bye' 退出): ");
            
            // 读取用户输入并发送到服务器
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
                
                // 读取服务器响应
                String response = in.readLine();
                System.out.println("服务器响应: " + response);
                
                if ("bye".equalsIgnoreCase(userInput)) {
                    break;
                }
                System.out.print("请输入消息: ");
            }
            
        } catch (UnknownHostException e) {
            System.err.println("未知主机: " + hostname);
        } catch (IOException e) {
            System.err.println("I/O 错误: " + e.getMessage());
        }
    }
}